<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 保存用户配置接口 - 管理员信息保存
 * 尊重劳动成果是一种美德
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

// 日志记录函数已禁用
// function writeLog($message) {}

try {
    // writeLog('用户配置保存请求开始');
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        // writeLog('错误: 请求方法不正确');
        echo json_encode(['success' => false, 'message' => '请求方法错误']);
        exit;
    }

    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $dingtalkId = $_POST['dingtalk_id'] ?? '';
    $wechatId = $_POST['wechat_id'] ?? '';
    $feishuId = $_POST['feishu_id'] ?? '';

    // 日志已禁用
    // writeLog("配置参数 - Username: {$username}, Phone: {$phone}, DingtalkId: {$dingtalkId}, WechatId: {$wechatId}, FeishuId: {$feishuId}");

    if (empty($username) || empty($password)) {
        // writeLog('错误: 缺少必要参数');
        echo json_encode(['success' => false, 'message' => '用户名和密码不能为空']);
        exit;
    }

    $configFile = __DIR__ . '/../config.php';

    if (!file_exists($configFile)) {
        // writeLog('错误: 配置文件不存在');
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        exit;
    }

    // writeLog('读取现有配置文件');
    $config = include $configFile;
    
    if (!is_array($config)) {
        // writeLog('错误: 配置文件格式不正确');
        echo json_encode(['success' => false, 'message' => '配置文件格式不正确']);
        exit;
    }

    // 更新或添加 admin_user 配置
    $config['admin_user'] = [
        'username' => $username,
        'password' => $password,
        'phone' => $phone,
        'dingtalk_id' => $dingtalkId,
        'wechat_id' => $wechatId,
        'feishu_id' => $feishuId
    ];

    // 生成新的配置文件内容
    $configContent = "<?php\n/**\n * 氚云API管理系统配置文件\n * Alyr.net 企业级配置管理\n */\n\n// 氚云API配置\nreturn " . var_export($config, true) . ";\n";

    // writeLog('尝试保存配置到文件');
    if (file_put_contents($configFile, $configContent)) {
        // writeLog('用户配置保存成功');
        echo json_encode(['success' => true, 'message' => '用户配置保存成功']);
    } else {
        // writeLog('错误: 用户配置保存失败');
        echo json_encode(['success' => false, 'message' => '用户配置保存失败']);
    }
} catch (Exception $e) {
    $errorMsg = $e->getMessage();
    // writeLog("系统错误: {$errorMsg}");
    echo json_encode(['success' => false, 'message' => '系统错误: ' . $errorMsg]);
}
exit;